package top.lixunda.books3.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.lixunda.books3.entity.User;
import top.lixunda.books3.entity.UserBind;
import top.lixunda.books3.model.Message;
import top.lixunda.books3.service.UserService;
import top.lixunda.books3.service.VerifyService;
import top.lixunda.books3.util.Log;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private VerifyService verifyService;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Message tempLogin(String username, String password, String verify, boolean isSave,
                             HttpSession session, HttpServletResponse response){
        //1. 验证参数是否缺失
        if(username == null || password == null || verify == null)
            return Message.errorClientParamsMiss("参数缺失");
        //2. 验证参数格式
        boolean judge = userService.judgeAllFormat(username, password, verify);
        if(!judge){
            return Message.errorClientParamsFormat("参数格式错误");
        }
        //3. 验证验证码
        judge = verifyService.judgeLoginVerify(verify);
        if(!judge){
            return Message.errorClientVerify();
        }
        //4. 验证用户
        int loginJudge = userService.tempLogin(username, password);
        switch (loginJudge){
            case UserService.CODE_ERROR_PARAMS:
                return Message.errorClientParamsFormat().setMessage("账号格式不正确");
            case UserService.CODE_NO_USER:
                return Message.errorClientNoUser();
            case UserService.CODE_ERROR_PASS:
                return Message.errorClientErrPass();
            case UserService.CODE_SUCCESS:
                break;
        }
        //5. 设置自动登录凭证
        User user = (User) session.getAttribute("user");
        Log.d("---------------->  本次登录设置保存  "+isSave);
        if(isSave){
            Cookie cookie = new Cookie("save", "true");
            Cookie cookie1 = new Cookie("loginKey", userService.createLoginKey(user));
            cookie.setMaxAge(30*24*60*60);
            cookie1.setMaxAge(30*24*60*60);
            cookie.setPath("/");
            cookie1.setPath("/");
            response.addCookie(cookie);
            response.addCookie(cookie1);
        }else{
            response.addCookie(new Cookie("save", "false"));
            response.addCookie(new Cookie("loginKey", ""));
        }
        //6. 取出密码
        user.setPassword("");
        //7. 登陆成功
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("userBind", session.getAttribute("userBind"));

        return Message.success().setData(map);
    }

    @RequestMapping(value = "/logout")
    @ResponseBody
    public Message logout(HttpSession session, HttpServletRequest request, HttpServletResponse response){
        //1. 移除user和userBind
        Log.d("logout");
        session.removeAttribute("user");
        session.removeAttribute("userBind");
        User user = (User) session.getAttribute("user");
        UserBind userBind = (UserBind) session.getAttribute("userBind");
        Log.d("logout : user "+user+"\t\tuserbind "+userBind);
        //2. 关闭自动登录
        Cookie[] cookies = request.getCookies();
        if (null==cookies) {
            Log.d("----> 没有cookie==============");
        } else {
            int i = 0;
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("save") || cookie.getName().equals("loginKey")){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);// 立即销毁cookie
                    cookie.setPath("/");
                    System.out.println("被删除的cookie名字为:"+cookie.getName());
                    response.addCookie(cookie);
                    if(++i >= 2)
                        break;
                }
            }
        }
        //3. 返回下线成功
        return Message.success();
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Message register(@RequestParam(value = "nick") String nickname,
                            @RequestParam(value = "phon") String phone,
                            @RequestParam(value = "pass") String password,
                            @RequestParam(value = "veri") String verify,
                            @RequestParam(value = "sms") String sms){
        Log.d("register", "--------   nickname:"+nickname+"\tphone:"+phone+"\tpassword:"+password+"\tverify"+verify+"\tsms:"+sms);
        //1. 验证参数
        //a. 验证电话号码格式
        if(!userService.judgePhoneFormat(phone)){
            //电话号码错误
            return Message.errorClientErrPhone();
        }
        //b. 验证密码格式
        if(!userService.judgePasswordFormat(password)){
            return Message.errorClientPassFormat();
        }
        //2. 验证图片验证码
        if(!verifyService.judgeRegisterVerify(verify)){
            return Message.errorClientVerify();
        }
        //3. 验证短信验证码
        if(!verifyService.judgeRegisterSms(phone, sms)){
            return Message.errorClientSmsVerify();
        }
        //4. 判断手机号码是否已经注册过了
        if(userService.doublePhoneUser(phone)){
            return Message.errorClientDoublePhone();
        }
        //5. 进行注册
        User user = userService.register(nickname, phone, password);
        if(user != null){
            return Message.successData(user).setMessage("注册成功");
        }
        return Message.errorServer("注册失败");
    }

}
